package kr.co.onc.common;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import kr.co.onc.util.JsonUtil;


public class BaseModel {
	/**
	 * MODEL 정보 Map 으로 변환
	 * @return Map<String, Object>
	 */
	public Map<String, Object> toMap()
	{
		Map<String, Object> map = new HashMap<String, Object>();
		
		Method[] methods = this.getClass().getMethods();
		for(int i=0; i<methods.length; i++)
		{
			String strMethodName = methods[i].getName();
			
			if(strMethodName.startsWith("get"))
			{
				String strFieldName = strMethodName;
				strFieldName = strFieldName.replaceFirst("get", "");
				strFieldName = strFieldName.substring(0, 1).toLowerCase() + strFieldName.substring(1);
				
				if(strFieldName.equals("class")) continue;
				
				try
				{
					map.put(strFieldName, methods[i].invoke(this));
				}
				catch(Exception e)
				{
				}
			}
		}
		
		return map;
	}
	
	/**
	 * MODEL 정보 Map 으로 변환
	 * @return Map<String, Object>
	 */
	public Map<String, Object> toMapUppercase()
	{
		Map<String, Object> map = new HashMap<String, Object>();
		
		Method[] methods = this.getClass().getMethods();
		for(int i=0; i<methods.length; i++)
		{
			String strMethodName = methods[i].getName();
			
			if(strMethodName.startsWith("get"))
			{
				String strFieldName = strMethodName;
				strFieldName = strFieldName.replaceFirst("get", "");
				strFieldName = strFieldName.substring(0, 1).toUpperCase() + strFieldName.substring(1).toUpperCase();
				
				
				if(strFieldName.equals("class")) continue;
				
				try
				{
					map.put(strFieldName, methods[i].invoke(this));
				}
				catch(Exception e)
				{
				}
			}
		}
		
		return map;
	}
	
	
	/**
	 * MODEL 정보 JSON 문자열로 변환
	 * @return JSON 문자열
	 */
	public String toString()
	{
		return JsonUtil.Object2String(this);
	}
	
	
	/**
	 * MODEL 정보에 자료 삽입
	 * @param data
	 */
	public void push(Object data)
	{
		Method[] methods = data.getClass().getMethods();
		for(int i=0; i<methods.length; i++)
		{
			String strMethodName = methods[i].getName();
			try
			{
				if(strMethodName.startsWith("get"))
				{
					this.getClass().getMethod(strMethodName.replaceFirst("get", "set"), methods[i].getReturnType()).invoke(this, methods[i].invoke(data));
				}
				else if(strMethodName.startsWith("is"))
				{
					this.getClass().getMethod(strMethodName.replaceFirst("is", "set"), methods[i].getReturnType()).invoke(this, methods[i].invoke(data));
				}
			}
			catch(NoSuchMethodException e)
			{
			}
			catch(IllegalArgumentException e)
			{
			}
			catch(Exception e)
			{
			}
		}
	}
}
